#!/usr/bin/env python
# encoding: utf-8
"""
Copyright 2011, 2012 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import os, time, logging, threading

class WatchFolder:
	def __init__(self,path,timedelta=10.0):
		assert os.path.isdir(path)
		assert timedelta > 0
		self._path = path
		self._files = dict()
		self._exit = False
		self._timedelta = timedelta
	# properties
	def get_exit(self):
		return self._exit
	def set_exit(self,value):
		self._exit = value
	def get_path(self):
		return self._path
	exit = property(get_exit,set_exit)
	path = property(get_path)

	# methods
	def scan(self):
		# scan for new files
		new_files = dict([(f, None) for f in os.listdir(self._path)])
		added_files = [f for f in new_files if (not f in self._files and self.valid_filename(f))]
		deleted_files = [f for f in self._files if (not f in new_files and self.valid_filename(f))]
		# report on changes
		if added_files:
			self.added(added_files)
		if deleted_files:
			self.deleted(deleted_files)
		# reset files
		self._files = new_files
	def runloop(self):
		scantime = None
		while not self.exit:
			if scantime==None or (time.time() - scantime) > self._timedelta:
				logging.debug("SCANNING")
				self.scan()
				scantime = time.time()
			time.sleep(0.5)
	# These are the messages which need to be overridden
	def valid_filename(self,filename):
		if filename.startswith('.') or filename.endswith('~'):
			return False
		return True
	def added(self,paths):
		pass
	def deleted(self,paths):
		pass
		
